import sys
import os
from flask import Flask, request, send_file
import qrcode
import datetime

app = Flask(__name__)

# 获取当前脚本文件所在的目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_DIR = os.path.join(BASE_DIR, 'static')
LOG_DIR = os.path.join(BASE_DIR, 'log')

if len(sys.argv) != 3:
    print("Usage: python3 QR_Visitor_Tracker.py <server>")
    sys.exit(1)

server = sys.argv[1]  # Define the server variable based on command line argument
port = sys.argv[2]
portqr = ":" + str(port)

# Ensure that the static and log folders exist
if not os.path.exists(STATIC_DIR):
    os.makedirs(STATIC_DIR)

if not os.path.exists(LOG_DIR):
    os.makedirs(LOG_DIR)

@app.route('/')
def index():
    return f"Visit    http://{server}{portqr}/generate_qr/xxx(visitor_name)   to generate a QR code for the visitor. After the visitor scans the QR code, the information will be automatically logged to the terminal and a file."

@app.route('/generate_qr/<visitor_name>')
def generate_qr(visitor_name):
    visitor_purpose = "Visitor"

    # Log visitor information to file
    with open(os.path.join(LOG_DIR, 'QR_visitor_logs.txt'), 'a') as f:
        f.write(f"Visitor Name: {visitor_name}\n")
        f.write(f"Purpose: {visitor_purpose}\n")
        f.write(f"Request Time: {datetime.datetime.now()}\n")
        f.write("--------------------------\n")

    # Generate QR code
    success = generate_qr_code(visitor_name, visitor_purpose)

    if success:
        return send_file(os.path.join(STATIC_DIR, f"{visitor_name}_QR.png"), mimetype='image/png')
    else:
        return "Failed to generate QR code", 500

@app.route('/scan_qr/<visitor_name>')
def scan_qr(visitor_name):
    # Get visitor information
    ip_addr = request.remote_addr
    user_agent = request.headers.get('User-Agent')
    referer = request.headers.get('Referer')
    cookies = request.cookies
    request_time = datetime.datetime.now()
    request_path = request.path

    # Print to the terminal
    print(f"Visitor Name: {visitor_name}")
    print(f"IP Address: {ip_addr}")
    print(f"User Agent: {user_agent}")
    print(f"Referer: {referer}")
    print(f"Cookies: {cookies}")
    print(f"Request Time: {request_time}")
    print(f"Request Path: {request_path}")
    print("--------------------------")

    # Log to file
    with open(os.path.join(LOG_DIR, 'visitor_logs.txt'), 'a') as f:
        f.write(f"Visitor Name: {visitor_name}\n")
        f.write(f"IP Address: {ip_addr}\n")
        f.write(f"User Agent: {user_agent}\n")
        f.write(f"Referer: {referer}\n")
        f.write(f"Cookies: {cookies}\n")
        f.write(f"Request Time: {request_time}\n")
        f.write(f"Request Path: {request_path}\n")
        f.write("--------------------------\n")

    return "Sorry, this website is still under construction."

def generate_qr_code(visitor_name, visitor_purpose):
    try:
        # Construct visitor information string
        visitor_info = f"http://{server}{portqr}/scan_qr/{visitor_name}"  # Use the server variable

        # Generate QR code
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qr.add_data(visitor_info)
        qr.make(fit=True)

        # Create and save the QR code image
        qr_img = qr.make_image(fill_color="black", back_color="white")
        qr_img.save(os.path.join(STATIC_DIR, f"{visitor_name}_QR.png"))  # Save to the static folder

        print(f"QR code generated and saved as {os.path.join(STATIC_DIR, f'{visitor_name}_QR.png')}")  # Debug information
        return True
    except Exception as e:
        print(f"Error occurred while generating QR code: {e}")  # Debug information
        return False

if __name__ == '__main__':
    app.run(host=server, port=port)

# pip install Flask qrcode[pil]
# ©sansjtw 金条k
# 编写时间:2024.6.15 16:05